package com.example.tests;

import android.test.ActivityInstrumentationTestCase2;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.R;
import com.example.db.db;
import com.example.model.UserList;
import com.example.views.MainActivity;
import com.example.model.User;

public class LoginTest extends ActivityInstrumentationTestCase2 <MainActivity> {
	
	
	private MainActivity mainActivity;
	private EditText username;
	private EditText password;
	private TextView error;
	private Button loginButton;
	private UserList userList;
	private User user;
	
	
	public LoginTest() {
		super(MainActivity.class);
	}
	
	public void setUp() {
		setActivityInitialTouchMode(false);
		

		user = new User("Username", "Password");
		userList = new UserList();
		mainActivity = getActivity();
		username = (EditText) mainActivity.findViewById(com.example.R.id.username_edit);
		password = (EditText) mainActivity.findViewById(com.example.R.id.password_edit);
		loginButton = (Button) mainActivity.findViewById(com.example.R.id.login_button);
		error = (TextView) mainActivity.findViewById(com.example.R.id.login_error_text);
		userList.add(user);
	}
	
	public void testUserExists(){
		try {
			runTestOnUiThread(new Runnable() {
				@Override
				public void run() {
					getLogin("wrong", "password");
					assertEquals("User not found", error.getText());
				}
			});
		}
		catch (Throwable e) {
			e.printStackTrace();
		}
	}

	
	public void testCorrectPassword(){
		try {
			runTestOnUiThread(new Runnable() {
				@Override
				public void run() {
					getLogin("cayla", "wrong");
					assertEquals("Wrong password, try again.", error.getText());
				}
			});
		}
		catch (Throwable e) {
			e.printStackTrace();
		}
	}

	
	private void getLogin(String name, String pass){
		username.requestFocus();
		sendKeys(name);
		password.requestFocus();
		sendKeys(pass);
		loginButton.performClick();
	}
	
}